/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import dao.Dao;
import entidades.Campeonato;
import entidades.Jogo;
import entidades.Palpite;
import entidades.Rodada;
import entidades.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.Util;

/**
 *
 * @author Marco Antonio
 */
@WebServlet(name = "ServletPalpites", urlPatterns = {"/ServletPalpites"})
public class ServletPalpites extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletPalpites</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletPalpites at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String operacao = request.getParameter("op");
        HttpSession session = request.getSession(true);
        if (operacao.equals("Selecionar Campeonato")) {
            int id = Integer.parseInt(request.getParameter("idcampeonato"));
            if (session.getAttribute("campeonatoPalpites") != null) {
                session.removeAttribute("campeonatoPalpites");
            }
            Campeonato c = new Dao<Campeonato>(Campeonato.class).get(id);
            session.setAttribute("campeonatoPalpites", c);
        } else if (operacao.equals("Selecionar Rodada")) {
            int id = Integer.parseInt(request.getParameter("idrodada"));
            if (session.getAttribute("rodadaPalpites") != null) {
                session.removeAttribute("rodadaPalpites");
            }
            Rodada r = new Dao<Rodada>(Rodada.class).get(id);
            session.setAttribute("rodadaPalpites", r);
        } else if (operacao.equals("Salvar")) {
            int idCampeonato = ((Campeonato) session.getAttribute("campeonatoPalpites")).getId();
            int idRodada = ((Rodada) session.getAttribute("rodadaPalpites")).getId();
            Rodada rodada = new Dao<Rodada>(Rodada.class).get(idRodada);
            Date dataAtual = new Date();
            if (dataAtual.after(rodada.getInicioPalpites()) && dataAtual.before(rodada.getTerminoPalpites())) {
                for (Jogo j : new Dao<Jogo>(Jogo.class).list()) {
                    if (j.getRodada().getId() == idRodada && 
                            j.getRodada().getCampeonato().getId() == idCampeonato) {
                        Palpite p = new Palpite();
                        p.setJogo(j);
                        p.setUsuario((Usuario) session.getAttribute("logado"));
                        if (request.getParameter("placarM" + j.getId()).isEmpty()) {
                            p.setGolMandante(-1);
                        } else {
                            p.setGolMandante(Integer.parseInt(request.getParameter("placarM" + j.getId())));
                        }
                        if (request.getParameter("placarV" + j.getId()).isEmpty()) {
                            p.setGolVisitante(-1);
                        } else {
                            p.setGolVisitante(Integer.parseInt(request.getParameter("placarV" + j.getId())));
                        }
                        new Dao<Palpite>(Palpite.class).insert(p);
                    }
                }
            }
        } else if (operacao.equals("Editar")) {
            int idRodada = ((Rodada) session.getAttribute("rodadaPalpites")).getId();
            Usuario logado = (Usuario) session.getAttribute("logado");
            Rodada rodada = new Dao<Rodada>(Rodada.class).get(idRodada);
            Date dataAtual = new Date();
            if (dataAtual.after(rodada.getInicioPalpites()) && dataAtual.before(rodada.getTerminoPalpites())) {
                List<Palpite> palpites = new Dao<Palpite>(Palpite.class).list();
                for (Palpite p : palpites) {
                    if (p.getJogo().getRodada().getId() == idRodada && p.getUsuario().getEmail().equals(logado.getEmail())) {
                        if (request.getParameter("placarM" + p.getJogo().getId()).isEmpty()) {
                            p.setGolMandante(-1);
                        } else {
                            p.setGolMandante(Integer.parseInt(request.getParameter("placarM" + p.getJogo().getId())));
                        }
                        if (request.getParameter("placarV" + p.getJogo().getId()).isEmpty()) {
                            p.setGolVisitante(-1);
                        } else {
                            p.setGolVisitante(Integer.parseInt(request.getParameter("placarV" + p.getJogo().getId())));
                        }                        
                        new Dao<Palpite>(Palpite.class).update(p);
                    }
                }
            }
        }
        response.sendRedirect("palpites.jsp");
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
